<template>
  <div class="app-container product-list">
    <transition name="el-zoom-in-top">
      <el-card class="box-card" shadow="always" v-show="showSearch">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="产品名称" prop="goodsName">
            <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="供应商" prop="supplierName">
            <el-input v-model="queryParams.supplierName" placeholder="请输入供应商" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="产品分类" prop="warehouseCode">
            <el-tree-select
              :props="{ value: 'id', label: 'classifyName', children: 'children' }"
              v-model="queryParams.classifyId"
              :data="categoryList"
              clearable
              :render-after-expand="false"
            />
          </el-form-item>
          <el-form-item label="产品品牌" prop="brandName">
            <el-input v-model="queryParams.brandName" placeholder="请输入产品品牌" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="产品货号" prop="itemNo">
            <el-input v-model="queryParams.itemNo" placeholder="请输入产品货号" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="产品来源" prop="goodsType">
            <el-select clearable v-model="queryParams.goodsType" placeholder="请选择产品来源">
              <el-option v-for="(item, index) in goods_source" :key="index" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供货方式" prop="supplyMode">
            <el-select clearable v-model="queryParams.supplyMode" placeholder="请选择供货方式">
              <el-option v-for="item in drop_shipping" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="集采价" prop="costPriceMin">
            <el-col :span="11">
              <el-input v-model="params.costPriceMin" placeholder="集采价" clearable @keyup.enter="handleQuery" />
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">~</el-col>
            <el-col :span="11">
              <el-input v-model="params.costPriceMax" placeholder="集采价" clearable @keyup.enter="handleQuery" />
            </el-col>
          </el-form-item>
          <el-form-item label="批发价" prop="wholesalePriceMin">
            <el-col :span="11">
              <el-input v-model="params.wholesalePriceMin" placeholder="批发价" clearable @keyup.enter="handleQuery" />
            </el-col>
            <el-col class="line" :span="2" style="text-align: center">~</el-col>
            <el-col :span="11">
              <el-input v-model="params.wholesalePriceMax" placeholder="批发价" clearable @keyup.enter="handleQuery" />
            </el-col>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="更新时间">
            <el-date-picker
              v-model="updateDateRange"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </transition>
    <div class="content">
      <div v-show="tableHeight && showTree" :style="`height: ${tableHeight}px;position: relative;`">
        <div class="left" :style="`height: ${tableHeight}px;`">
          <div class="left-top">
            <div class="">商品分类</div>
            <div class="">
              <img style="width: 30px; height: 30px" @click="handleEdge" :src="showTree ? imgs[1] : imgs[0]" />
            </div>
          </div>
          <el-tree
            ref="classifyTreeRef"
            class="mt-2"
            node-key="id"
            :data="categoryList"
            :props="{ label: 'classifyName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="itemClick"
          />
        </div>
      </div>
      <el-card
        ref="table"
        shadow="always"
        :class="{ 'w-tree': showTree, 'w-all': !showTree }"
        :body-style="{ padding: '20px' }"
        style="margin-top: 10px"
      >
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" @click="handleAdd" v-hasPermi="['order:goods:add']">添加产品 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" :disabled="!multiple" @click="handleBatchDelete" v-hasPermi="['order:goods:remove']">删除 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button style="float: right; margin-right: 10px" type="danger" @click="handleCustom">自定义价格</el-button>
          </el-col>
          
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table
          class="product-table"
          :height="tableDefHeight"
          style="position: sticky; top: 50px; min-height: 550px"
          border
          v-loading="loading"
          :data="dataSource"
          scrollbar-always-on
          @row-dblclick="dbclick"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" :selectable="selectHandle" />
          <el-table-column label="#" type="index" width="55" align="center" fixed="left"> </el-table-column>
          <el-table-column label="商品图片" align="center" width="120" fixed="left">
            <template #default="scope">
              <ImagePreview :width="100" :height="100" :src="scope.row.packImg" :preview-src-list="[scope.row.packImg]" />
            </template> 
          </el-table-column>
          <el-table-column label="货号" align="center" prop="itemNo" width="100" fixed="left" />
          <el-table-column label="商品名称" align="left" prop="goodsName" min-width="120" fixed="left" />
          <el-table-column label="产品品牌" align="center" prop="brandName" width="150" />
          <el-table-column label="默认供应商" align="center" prop="supplierName" width="150" />
          <el-table-column label="产品来源" align="center" prop="goodsSource" width="80">
            <template #default="scope">
              {{ selectDictLabel(goods_source, scope.row.goodsType) }}
            </template>
          </el-table-column>
          <el-table-column label="分类" align="center" prop="classifyName" width="150" />
          <!-- <el-table-column label="商品编码" align="center" prop="goodsSku" /> -->
          <el-table-column label="商品规格" align="center" prop="goodsSize" />
          <el-table-column label="换算率" align="center" width="200">
            <template #default="scope">
              {{ getNnitRatios(scope.row) }}
            </template>
          </el-table-column>
          <!-- <el-table-column v-for="(item, index) in mx_material_price" :key="index" :label="item.label" align="center"
                :prop="item.value" :width="Math.max(item.label.length * 20, 80)">
                <template #default="scope">
                    {{ getPrice(scope.row, item) }}
                </template>
            </el-table-column> -->
          <el-table-column label="创建时间" align="center" prop="createTime" min-width="180" />
          <el-table-column label="更新时间" align="center" prop="updateTime" min-width="180" />
          <el-table-column label="审核状态" align="center" width="200">
            <template #default="scope">
              {{ selectDictLabel(material_audit_status, scope.row.auditStatus) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200" fixed="right">
            <template #default="scope">
              <!-- <el-button type="text"  @click="handleDetail(scope.row.orderId)">详情</el-button>
                  <el-divider direction="vertical"></el-divider> -->
              <el-button v-hasPermi="['order:goods:edit']" type="text" @click="handleEdit(scope.row)">编辑</el-button>
              <el-divider v-hasPermi="['order:goods:edit']" direction="vertical"></el-divider>
              <el-button v-hasPermi="['order:goods:remove']" type="text" @click="handleDelete(scope.row.id)">删除</el-button>
              <el-divider v-hasPermi="['order:goods:remove']" direction="vertical"></el-divider>
              <el-button v-hasPermi="['order:goods:edit']" type="text" @click="handleEditPrice(scope.row)">商品调价</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div class="fixed-icon" @click="handleEdge" v-show="!showTree">
      <el-icon>
        <DArrowRight />
      </el-icon>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page.sync="queryParams.pageNum"
      v-model:limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <addProductForm ref="modelForm" @ok="handleQuery"></addProductForm>
    <quoteForm ref="quoteForm"></quoteForm>
    <editPriceForm ref="editPriceForm" @ok="getList"></editPriceForm>
    <customPriceListForm ref="customPriceListForm"></customPriceListForm>
  </div>
</template>

<script>
import addProductForm from './modules/addProductForm.vue';
import quoteForm from './modules/quoteForm.vue';
import editPriceForm from './modules/editPriceForm.vue';
import listMixin from '@/mixins/listMixin';
import ImagePreview from '@/components/ImagePreview/index.vue';
import customPriceListForm from './modules/customPriceListForm.vue';
import zk from '@/assets/images/zhankai.svg';
import zd from '@/assets/images/zhedie.svg';
export default {
  name: 'productList',
  dicts: ['mx_material_price'],
  components: {
    addProductForm,
    quoteForm,
    editPriceForm,
    ImagePreview,
    customPriceListForm
  },
  mixins: [listMixin],
  data() {
    return {
      params: {},
      showTree: true,
      dateRange: [],
      updateDateRange: [],
      categoryList: [],
      mx_material_price: [],
      goods_source: [],
      drop_shipping: [],
      material_audit_status: [], //商品审核状态
      urls: {
        list: '/order/goods/list',
        delete: '/order/goods'
      },
      imgs: [zk, zd],
      tableHeight: 0,
      tableDefHeight: 0,
      currentIndex: ''
    };
  },
  computed: {
    tableDefHeight() {
      this.$nextTick(() => {
        console.log('document.documentElement.clientHeight :>> ', document.documentElement.clientHeight);
        if (this.dataSource.length < 10) {
          return document.documentElement.clientHeight - 480 + 'px';
        } else {
          return 'auto';
        }
      });
    }
  },
  mounted() {
    this.getCommonCategoryAllList();
    this.getDicts(['mx_material_price', 'goods_source', 'material_audit_status', 'drop_shipping']);
    this.$nextTick(() => {
      setTimeout(() => {
        this.tableHeight = this.$refs.table.$el.scrollHeight;
      }, 200);
    });
    // 获取屏幕高度
    this.tableDefHeight = document.documentElement.clientHeight - 480;
  },
  methods: {
    listAfter() {
      this.$nextTick(() => {
        this.tableHeight = this.$refs.table.$el.scrollHeight;
      });
    },
    handleEditPrice(row) {
      console.log('this.max_material_price :>> ', this.mx_material_price);
      this.$refs.editPriceForm.edit(row, this.mx_material_price);
    },
    getPrice(row, child) {
      let defaultPriceArr = ['unitName', 'costPrice', 'purchasePrice', 'wholesalePrice', 'salePrice', 'upsetPrice', 'retailPrice'];
      if (defaultPriceArr.includes(child.value)) {
        return row[child.value];
      } else {
        let item = (row.goodsRedisList || []).find((item) => item.priceName == child.value);
        return item ? item.price : '';
      }
    },
    
    handleCustom() {
      this.$refs.customPriceListForm.show();
    },
    itemClick(data) {
      this.currentIndex = data.id;
      console.log('this.currentIndex :>> ', this.currentIndex);
      this.categoryList.forEach((data) => {
        data.active = false;
      });
      data.active = !data.active;
      this.queryParams.classifyId = data.id;
      this.getList();
    },

    /** 转换数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.classifyName,
        children: node.children
      };
    },
    getQueryParams() {
      let params = Object.assign({}, this.queryParams);
      params.params = { ...this.params };
      if (this.dateRange && this.dateRange.length) {
        params.params['createBeginTime'] = this.dateRange[0] + ' 00:00:00';
        params.params['createEndTime'] = this.dateRange[1] + ' 23:59:59';
      }
      if (this.updateDateRange && this.updateDateRange.length) {
        params.params['updateBeginTime'] = this.updateDateRange[0] + ' 00:00:00';
        params.params['updateEndTime'] = this.updateDateRange[1] + ' 23:59:59';
      }
      return params;
    },

    /**
     * @重置查询条件
     */
    resetQuery() {
      this.queryParams = {
        //查询条件
        pageNum: 1,
        pageSize: 10
      };
      (this.dateRange = []), (this.updateDateRange = []), (this.params = {});
      this.$refs.classifyTreeRef.setCurrentKey(null);
      this.getList();
    },

    getNnitRatios(row) {
      let unitRatiosStr = '';
      const def = row.unitVoList[0];
      const unitVoList = row.unitVoList.slice(1).reverse();
      // 数组长度可能为0,1,2,3，需要返回 1箱=2瓶=3盒=4个这种格式,默认第一个为基准单位
      if (unitVoList.length == 1) {
        unitRatiosStr = `1${unitVoList[0].name}=${unitVoList[0].ratio}${def.name}`;
      } else if (unitVoList.length == 2) {
        const ratio = +((unitVoList[0].ratio / unitVoList[1].ratio) * def.ratio).toFixed(2);
        unitRatiosStr = `1${unitVoList[0].name}=${ratio}${unitVoList[1].name}=${unitVoList[0].ratio}${def.name}`;
      }
      return unitRatiosStr.indexOf('null') > -1 ? '-' : unitRatiosStr;
    },
    handleEdge() {
      this.showTree = !this.showTree;
    }
  }
};
</script>

<style type="text/css" lang="scss" scoped>
.left {
  width: 240px;
  border: 1px solid #e6ebf5;
  border-radius: 4px;
  overflow-x: hidden;
  overflow-y: auto;
  padding-bottom: 60px;
  margin-top: 10px;
  background-color:#fff;
  border-radius: 12px;

  .fodder_list {
    z-index: 20;

    .fodder_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 20px;
      cursor: pointer;

      .box {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        svg {
          margin-right: 10px;
        }

        .fodder_name {
          font-size: 14px;
          color: #303133;
          width: 84px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .fodder_item.active,
    .fodder_item:hover {
      background-color: #f5f5f5;
    }
  }
}

.left-top {
  display: flex;
  justify-content: space-between;
  padding: 6px 20px;
  border-bottom: 1px solid #e6ebf5;
  align-items: center;

  .box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    font-size: 24px;
    color: #303133;
    font-weight: bold;
  }
}

.fixed-icon {
  position: fixed;
  //left: 0;
  top: 400px;
  z-index: 999;
  background-color: #409eff;
  padding: 12px 2px;
  color: #fff;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  display: flex;
  cursor: pointer;
}

.content {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.w-tree {
  width: calc(100% - 260px);
}

.w-all {
  width: 100%;
}
</style>
<style>
.product-table .el-table__empty-block {
  height: 550px !important;
}

.product-table .el-scrollbar__view {
  min-height: 550px !important;
}

.product-list .el-form-item .el-form-item__content {
  width: 200px !important;
}

.product-list .el-form--inline .el-input {
  width: 100% !important;
}
</style>